function f = est_obj(args)

%global K_tm1 L_tm1 VNAX_tm1 VmJ_tm1 VmnJ_tm1 pnJ_tm1 pJ_tm1 px_tm1 ...
%    K_t L_t VNAX_t VmJ_t VmnJ_t pnJ_t pJ_t px_t

global sample_est nu_i mu

%sample = csvread('sample_static_jpn.txt');

sample = sample_est;


%K_tm1 = 1/2*sample(:,1)/0.1 ;
%K_tm1 = 1/4*sample(:,1)/0.1 ;
K_tm1 = 1/4*sample(:,1)/0.06 ;
L_tm1 = sample(:,2);
VNAX_tm1 = sample(:,3);
VmJ_tm1 = sample(:,4);
VmnJ_tm1 = sample(:,5);
pnJ_tm1 = sample(:,6);
pJ_tm1 = sample(:,7);
px_tm1 = sample(:,8);
%K_t = 1/2*sample(:,1)/0.1 ;
%K_t = 1/4*sample(:,1)/0.1 ;
K_t = 1/4*sample(:,1)/0.07 ;
L_t = sample(:,2);
VNAX_t = sample(:,9);
VmJ_t =  sample(:,10);
VmnJ_t = sample(:,11);
pnJ_t = sample(:,12);
pJ_t = sample(:,13);
px_t = sample(:,14);
cm = sample(:,15);

%alternate way of doing the labor/capital
%K_tm1 = 1/2*sample(:,18)/0.1;
K_tm1 = 1/2*sample(:,18)/0.07;
L_tm1 = sample(:,16);
%K_t = 1/2*sample(:,19)/0.1;
K_t = K_tm1;
L_t = sample(:,17);

ind = sample(:,20);
scale= sample(:,21);

% Creating the Weight vector (change contents to employment if you want)

weight = VNAX_tm1;
%weight = L_tm1;

% Winsorizing and scaling up non japanese intermediate inputs

PCT=prctile(scale,[10 90]);
for i=1:length(scale)
	if scale(i)<PCT(1)
		scale(i)=PCT(1);
	else if scale(i)>PCT(2)
		scale(i)=PCT(2);
	end
	end
end

VmnJ_tm1=VmnJ_tm1.*scale;
VmnJ_t = VmnJ_t.*scale;

%mu  = args(1);
%mu  = 0.5;%-0.2;
om  = args(1);
psi = args(2);

alpha = 1/3;

nu_i = (VmnJ_tm1./VmJ_tm1)./((pJ_tm1./pnJ_tm1).^(om-1) + ...
    (VmnJ_tm1./VmJ_tm1));

M_tm1=(nu_i.^(1/om).*(VmnJ_tm1./pnJ_tm1).^((om-1)/om)+(1-nu_i).^(1/om).*(VmJ_tm1./pJ_tm1).^((om-1)/om)).^(om/(om-1));

mu = (1./(((K_tm1.^alpha.*L_tm1.^(1-alpha))./M_tm1).^(psi-1).*(1./(1-cm)-1).^psi + 1)); % should be mu.^(1/psi)_i

%mu(1:10)
%mu = mean(mu);

% generating group means
[muind, indgrp]=grpstats(mu, ind, {'mean','gname'});
indgrp2=cellfun(@str2num,indgrp);

mu_temp=[mu ind];

for i=1:length(indgrp2)
	for j=1:length(mu_temp)
		if mu_temp(j,2)==indgrp2(i)
			mu_temp(j,1)=muind(i);
		end
	end
end

mu=mu_temp(:,1);

temp1 = (mu.^(1/psi).*(px_tm1.*K_tm1.^alpha.*L_tm1.^(1-alpha)).^((psi-1)/psi) + ...
    (1-mu).^(1/psi).*(px_tm1./pJ_tm1.*VmJ_tm1).^((psi-1)/psi).* ...
    ((nu_i.^(1/om).*(pJ_tm1./pnJ_tm1.*VmnJ_tm1./VmJ_tm1).^((om-1)/om) + ...
    (1-nu_i).^(1/om)).^(om/(om-1))).^((psi-1)/psi)).^(psi/(psi-1));

phi_i_tild = VNAX_tm1./temp1;

temp2 = (mu.^(1/psi).*(px_t.*K_t.^alpha.*L_t.^(1-alpha)).^((psi-1)/psi) + ...
    (1-mu).^(1/psi).*(px_t./pJ_t.*VmJ_t).^((psi-1)/psi).* ...
    ((nu_i.^(1/om).*(pJ_t./pnJ_t.*VmnJ_t./VmJ_t).^((om-1)/om) + ...
    (1-nu_i).^(1/om)).^(om/(om-1))).^((psi-1)/psi)).^(psi/(psi-1));

%disp(mu(1:10))
%disp(nu_i(1:30))
%disp(mean(nu_i))
%disp(mu(1:10))

% WEIGHTING THE ERRORS

eps_NA = sqrt(weight).*(log(VNAX_t) - log(phi_i_tild.*temp2));

f = eps_NA'*eps_NA;

end